package cn.controller;

import cn.common.*;
import cn.filter.LoginCheck;
import cn.kpi.common.Excel.domain.SubheadModel;
import cn.kpi.common.Excel.export.ExportConfigFactory;
import cn.kpi.common.Excel.export.FileExportor;
import cn.kpi.common.Excel.export.domain.common.ExportCell;
import cn.kpi.common.Excel.export.domain.common.ExportConfig;
import cn.kpi.common.Excel.export.domain.common.ExportResult;
import cn.kpi.common.Excel.importfile.FileImportExecutor;
import cn.kpi.common.Excel.importfile.domain.common.Configuration;
import cn.kpi.common.Excel.importfile.domain.common.ImportResult;
import cn.kpi.common.Excel.importfile.impl.XmlConfigParser;
import cn.kpi.common.Excel.util.ReflectionUtils;
import cn.kpi.entity.attendance.AttTbBatchEntity;
import cn.kpi.entity.payassessment.*;
import cn.kpi.entity.sys.Configure;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.service.common.IOrgSummaryService;
import cn.kpi.service.payassessment.IPayAssessmentService;
import cn.kpi.service.payassessment.impl.PayAssessmentServiceImpl;
import cn.kpi.service.sys.IConfigureService;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IUserService;
import org.apache.camel.language.simple.FileLanguage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.kpi.common.utils.DateUtils.*;

@Controller
@RequestMapping("payass")
public class PayAssessionController extends BaseController {
    @Autowired
    private IConfigureService configureService;

    @Autowired
    private IPayAssessmentService iPayAssessmentService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IOrgService iOrgService;

    @Autowired
    private IOrgSummaryService iOrgSummaryService;

    //region 规则页面相关
    @ResponseBody
    @RequestMapping(value = "/get_assrule_list")
    public LayTable getRulePay() {
        List<AssessRulePay> lst = null;
        LayTable<AssessRulePay> layTable = new LayTable<AssessRulePay>();
        try {
            lst = iPayAssessmentService.getAssessRuleList();
            int iCount = lst.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/assessrule_pay")
    public String assRulePay(Model model) {
        //todo:可能需要加上权限
        return "payassessment/assessrule_pay";
    }

    @RequestMapping(value = "/assessrule_pay_edit")
    public String editRulePay(Model model) {
        //todo:可能需要加上权限
        return "payassessment/assessrule_pay_edit";
    }

    //规则编辑
    @RequestMapping(value = "/assessrule_pay_save", method = RequestMethod.POST)
    @ResponseBody
    public String assRulePaySave(@RequestBody AssessRulePayList uatmzpdsummary) throws Exception {
        List<AssessRulePay> assessRulePays = uatmzpdsummary.getUatmzpdsummary();
        int iResult = iPayAssessmentService.UpdateAssessRuleBatch(assessRulePays);
        return String.valueOf(iResult);
    }
    //endregion

    //region 工资单

    //1工资管理页面
    //获取组织机构
    @RequestMapping(value = "/user_pay")
    public String userPayinit(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            String year = getYear();
            String month = Integer.valueOf(getMonth()).toString();
            String title = "(" + year + "年" + month + "月)" + orglst.get(0).getOrgname() + "在职工资表";
            model.addAttribute("orglst", orglst);
            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("month", Integer.parseInt(month) - 1);
            model.addAttribute("status", 0);
        } catch (Exception ex) {
        }
        return "payassessment/user_pay_list";
    }

    @RequestMapping(value = "/user_pay_person")
    public String userPersonPayinit(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            String year = getYear();
            String month = Integer.valueOf(getMonth()).toString();
            String title = "(" + year + "年" + month + "月)" + orglst.get(0).getOrgname() + "在职工资表";
            model.addAttribute("orglst", orglst);
            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("month", Integer.parseInt(month) - 1);
            model.addAttribute("status", 1);
        } catch (Exception ex) {
        }
        return "payassessment/user_pay_list_person";
    }

    @RequestMapping(value = "/user_pay_ck_person")
    public String userPersonPayckinit(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            String year = getYear();
            String month = Integer.valueOf(getMonth()).toString();
            String title = "(" + year + "年" + month + "月)" + orglst.get(0).getOrgname() + "在职工资表";
            model.addAttribute("orglst", orglst);
            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("month", Integer.parseInt(month) - 1);
            model.addAttribute("status", 1);
        } catch (Exception ex) {
        }
        return "payassessment/user_pay_ck_list_person";
    }

    //工资表展示
    //todo:条件，完善
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_userpay_list")
    public LayTable<TUserPay> GetUserPayList(HttpServletRequest request) {
        List<TUserPay> lst = new ArrayList<>();
        LayTable<TUserPay> layTable = new LayTable<TUserPay>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String year = request.getParameter("year");
            String mouth = request.getParameter("month");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String status = request.getParameter("status");
            String orgs = "";//由orgid获取
            List<OrgEntity> orgEntities = new ArrayList<>();
            if (status.equals("1")) {//部门管理员只看到自己部门的
                orgEntities = getOrgEntities();

            } else {
                orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
            }

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }


            String where = "";
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND month=" + mouth;
            }

            if (orgs.length() > 0) {
                where += " AND orgid in (" + orgs + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND (realname like '%" + realname + "%' or cardno like '%" + realname + "%')";
            }
            if (status.equals("1")) {
                UserEntity userEntity = GetLoginUser();
                where += " AND cardno = '" + userEntity.getCardno()+"'";
            }

            countWhere = where;
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            where += " LIMIT " + beginrow + "," + endrow;
            TUserPay sumPay = new TUserPay();
            lst = iPayAssessmentService.getUserPayWhere(where);
            if (lst != null && lst.size() > 1 && status.equals("0")) {
                sumPay.setRealname("合计");
                for (TUserPay tUserPay : lst) {//80个字段，吐血，改为反射来完成。
                    for (Field field : tUserPay.getClass().getDeclaredFields()) {
                        String MethedName = field.getName();
                        if (MethedName.contains("num") && !MethedName.equals("num")) {
                            String sumdate = ReflectionUtils.executeMethod(sumPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String itemdate = ReflectionUtils.executeMethod(tUserPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            if(!sumdate.equals("")||!itemdate.equals("")) {//任意一个为空都跳过
                                String sum = String.valueOf(Float.valueOf(sumdate) + Float.valueOf(itemdate));
                                ReflectionUtils.executeSetMethod(sumPay, ReflectionUtils.returnSetMethodName(MethedName), sum);
                            }
                        }
                    }
                }
                lst.add(0, sumPay);
            }
            if (lst != null) {
                for (int i = 0; i < lst.size(); i++) {
                    lst.get(i).setNum(i);
                }
            }

            int iCount = iPayAssessmentService.getUserPayWhereCount(countWhere);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);
        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_userpay_ck_list")
    public LayTable<TUserPay> GetUserPayCKList(HttpServletRequest request) {
        List<TUserPay> lst = new ArrayList<>();
        LayTable<TUserPay> layTable = new LayTable<TUserPay>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String start = request.getParameter("start");
            String end = request.getParameter("endt");
            String realname = request.getParameter("realname");
//            String status = request.getParameter("atttype");
            String countWhere ="";


            String where = "";
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);

            SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM");
            if (start != null && start.length() > 0) {
                Date date=sDateFormat.parse(start);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH)+1;
                where += " AND year >= " + yeare +" AND month >= "+ monthe;
            }else{

                Date date = new Date();
                where += " AND year >= " + year+" AND month >= "+ month;
            }

            if (end != null && end.length() > 0) {
                Date date=sDateFormat.parse(end);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH)+1;
                where += " AND year <= " + yeare+" AND month <= "+ monthe;
            }else{
                Date date = new Date();
                where += " AND year <= " + year+ " AND month <= "+ month;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND (realname like '%" + realname + "%' or cardno like '%" + realname + "%')";
            }

            countWhere = where;
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            where += " LIMIT " + beginrow + "," + endrow;
            TUserPay sumPay = new TUserPay();
            lst = iPayAssessmentService.getUserPayWhere(where);
            if (lst != null && lst.size() > 1) {
                sumPay.setRealname("合计");
                for (TUserPay tUserPay : lst) {//80个字段，吐血，改为反射来完成。
                    for (Field field : tUserPay.getClass().getDeclaredFields()) {
                        String MethedName = field.getName();
                        if (MethedName.contains("num") && !MethedName.equals("num")) {
                            String sumdate = ReflectionUtils.executeMethod(sumPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String itemdate = ReflectionUtils.executeMethod(tUserPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String sum = String.valueOf(Math.round((Float.valueOf(sumdate) + Float.valueOf(itemdate))*100)/100);
                            ReflectionUtils.executeSetMethod(sumPay, ReflectionUtils.returnSetMethodName(MethedName), sum);
                        }
                    }
                }
                lst.add(0, sumPay);
            }
            if (lst != null) {
                for (int i = 0; i < lst.size(); i++) {
                    lst.get(i).setNum(i);
                }
            }

            int iCount = iPayAssessmentService.getUserPayWhereCount(countWhere);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);
        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    //导入页面初始化
    @RequestMapping(value = "/user_pay_list_import")
    public String userPayImportinit(HttpServletRequest request, Model model) {
        try {

            String year = request.getParameter("month");
            String month = request.getParameter("year");
            model.addAttribute("year", year);
            model.addAttribute("month", month);
        } catch (Exception ex) {
        }
        return "payassessment/user_pay_list_import";
    }

    //工资主表导入（状态表）
    @ResponseBody
    @RequestMapping(value = "/add_user_pay")
    public ExceResult AddVtdpUserTj(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String path = request.getParameter("path");


            int iResult = 0;
            //1.excle读取解析
            //a.获取模板
            XmlConfigParser xmlConfigParser = new XmlConfigParser();
            Configuration configuration = xmlConfigParser.getConfig("imuserpay.xml");
            //b.读取路径
            File file = new File(path);
            ImportResult mapMapResult = FileImportExecutor.importFile(configuration, file, file.getName(),"UserPay");
            List<Map<String, Object>> maps = mapMapResult.getResult();

            //2.数据加入当前用户的组织机构
            List<UserOrgMapEntity> userOrgMapEntities = iPayAssessmentService.getUserAndOrgid("");//全取出
            Map<String, Long> userOrgMap = new HashMap<>();
            for (UserOrgMapEntity userOrgMapEntity : userOrgMapEntities) {
                userOrgMap.put(userOrgMapEntity.getCardno(), userOrgMapEntity.getSzdw());
            }

            //3.拼接实体类,补上年月
            List<TUserPay> tUserPays = new ArrayList<>();
            for (Map<String, Object> map : maps) {
                TUserPay tUserPay = new TUserPay();
                tUserPay.setYear(Integer.valueOf(year));
                tUserPay.setMonth(Integer.valueOf(month));

                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Field fd = TUserPay.class.getDeclaredField(entry.getKey());
                    fd.setAccessible(true);
                    String value = entry.getValue().toString();
                    if (value != null && value.equals("")) value = "0";//如果计划是''，那么就赋值为0
                    fd.set(tUserPay, value);
                }
                String cardno = tUserPay.getCardno();//匹配上用户编码
                cardno = cardno.replace("x", "X");//转大写
                tUserPay.setCardno(cardno);//回写
                if (userOrgMap.containsKey(cardno)) {
                    tUserPay.setOrgid(userOrgMap.get(cardno));
                }
                tUserPays.add(tUserPay);
            }

            //插入数据
            iResult = iPayAssessmentService.updateUserPayList(tUserPays, year, month);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg(ex.getMessage());
        }
        return result;
    }


    //工资附件（内容）表导入

    /**
     * 实现文件上传,附件不建表保存//todo:以后改进
     * 返回保存路径
     */
    @RequestMapping(value = "/user_pay_upload", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult excleUpload(@RequestParam("file") MultipartFile file) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        if (null != file) {
            String myFileName = file.getOriginalFilename();// 文件原名称

            String fileName = Integer.toHexString(new Random().nextInt()) + "." + myFileName.
                    substring(myFileName.lastIndexOf(".") + 1);

            String basepath = ConfigOption.getInstance().getFileurl();
            String fileRoute = getSavePath(basepath);
            File fileDir = new File(fileRoute);
            if (!fileDir.exists()) { //如果不存在 则创建
                fileDir.mkdirs();
            }
            String path = fileRoute + fileName;
            File localFile = new File(path);
            try {
                file.transferTo(localFile);
                result.setCode(200);
                result.setResult(1);
                result.setMsg(path);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                result.setCode(500);
                result.setResult(0);
                result.setMsg(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                result.setCode(500);
                result.setResult(0);
                result.setMsg(e.getMessage());
            }
        } else {
            result.setCode(300);
            result.setResult(0);
            result.setMsg("上传文件为空！");
        }
        return result;
    }


    //工资附件（内容）表导出

    /**
     * 多个批量
     * 实现文件上传,附件不建表保存//todo:以后改进
     * 返回保存路径
     */
    @ResponseBody
    @RequestMapping(value = "/user_pay_export")
    public ExceResult excleExport(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("month");
            String owner = request.getParameter("owner");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND month=" + mouth;
            }

            if (owner != null & owner == "1") {
                UserEntity entity = getWebSysUserAttribute("UserEntity");
                String cardno = entity.getCardno();
                where += " AND cardno = " + cardno;
            }
            String fileName = "gongzibiao_" + new Random().nextInt() + ".xlsx";
            List<TUserPay> tUserPays = iPayAssessmentService.getUserPayWhere(where);
            TUserPay sumPay = new TUserPay();
            if (tUserPays.size() > 1) {
                sumPay.setRealname("合计");
                for (TUserPay tUserPay : tUserPays) {
                    for (Field field : tUserPay.getClass().getDeclaredFields()) {
                        String MethedName = field.getName();
                        if (MethedName.contains("num") && !MethedName.equals("num")) {
                            String sumdate = ReflectionUtils.executeMethod(sumPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String itemdate = ReflectionUtils.executeMethod(tUserPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String sum = String.valueOf(Float.valueOf(sumdate) + Float.valueOf(itemdate));
                            ReflectionUtils.executeSetMethod(sumPay, ReflectionUtils.returnSetMethodName(MethedName), sum);
                        }
                    }
                }
                tUserPays.add(0, sumPay);
            }


            for (int i = 0; i < tUserPays.size(); i++) {
                tUserPays.get(i).setNum(i);
            }

            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("房山公安分局"+mouth+"月工资表");
            subheadingVo.setSheetName("在职工资表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("exuserpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, tUserPays, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    //单用户导出
    @ResponseBody
    @RequestMapping(value = "/user_pay_export_person")
    public ExceResult excleExportPerson(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("month");
            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND month=" + mouth;
            }

            UserEntity userEntity = GetLoginUser();
            where += " AND cardno = " + userEntity.getCardno();

            String fileName = "gerengongzibiao_" + new Random().nextInt() + ".xlsx";
            List<TUserPay> tUserPays = iPayAssessmentService.getUserPayWhere(where);
            //生成一个MAP用户制作表头
            Map<String,Object>dataMap = ZJ_BeanToMapUtils.convertBeanToMap(tUserPays.get(0));

            TUserPay sumPay = new TUserPay();
            if (tUserPays.size() > 1) {
                sumPay.setRealname("合计");
                for (TUserPay tUserPay : tUserPays) {
                    for (Field field : tUserPay.getClass().getDeclaredFields()) {
                        String MethedName = field.getName();
                        if (MethedName.contains("num") && !MethedName.equals("num")) {
                            String sumdate = ReflectionUtils.executeMethod(sumPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String itemdate = ReflectionUtils.executeMethod(tUserPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String sum = String.valueOf(Float.valueOf(sumdate) + Float.valueOf(itemdate));
                            ReflectionUtils.executeSetMethod(sumPay, ReflectionUtils.returnSetMethodName(MethedName), sum);
                        }
                    }
                }
                tUserPays.add(0, sumPay);
            }


            for (int i = 0; i < tUserPays.size(); i++) {
                tUserPays.get(i).setNum(i);
            }

            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("房山公安分局"+mouth+"月工资表");
            subheadingVo.setSheetName("在职工资表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("exuserpay.xml");
            //根据实际是否包括的内容来生生成模板
            List<ExportCell> originCell = exportConfig.getExportCells();
            List<ExportCell> newCell = new ArrayList<>();
            for (ExportCell exportCell : originCell) {
                String key = exportCell.getAlias();
                if(dataMap.containsKey(key)){
                    if(dataMap.get(key)!=null&& !dataMap.get(key).toString().equals("")){
                        if(isNumeric(dataMap.get(key).toString())){
                            Long num = Long.valueOf(dataMap.get(key).toString());
                            if(num!=0l)
                                newCell.add(exportCell);
                        }
                        else{
                            newCell.add(exportCell);
                        }

                    }
                }
            }
            exportConfig.setExportCells(newCell);//处理过的小表头

            //excle方法继续
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, tUserPays, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    //单用户导出
    @ResponseBody
    @RequestMapping(value = "/user_pay_export_ck_person")
    public ExceResult excleExportCKPerson(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String start = request.getParameter("start");
            String end = request.getParameter("endt");
            String realname = request.getParameter("realname");
//            String status = request.getParameter("atttype");
            String countWhere ="";


            String where = "";
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);

            SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM");
            if (start != null && start.length() > 0) {
                Date date=sDateFormat.parse(start);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH)+1;
                where += " AND year >= " + yeare +" AND month >= "+ monthe;
            }else{

                Date date = new Date();
                where += " AND year >= " + year+" AND month >= "+ month;
            }

            if (end != null && end.length() > 0) {
                Date date=sDateFormat.parse(end);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH)+1;
                where += " AND year <= " + yeare+" AND month <= "+ monthe;
            }else{
                Date date = new Date();
                where += " AND year <= " + year+ " AND month <= "+ month;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND (realname like '%" + realname + "%' or cardno like '%" + realname + "%')";
            }

            String fileName = "gerengongzibiaock_" + new Random().nextInt() + ".xlsx";
            List<TUserPay> tUserPays = iPayAssessmentService.getUserPayWhere(where);
            //生成一个MAP用户制作表头
            Map<String,Object>dataMap = ZJ_BeanToMapUtils.convertBeanToMap(tUserPays.get(0));

            TUserPay sumPay = new TUserPay();

                sumPay.setRealname("合计");
                for (TUserPay tUserPay : tUserPays) {//导出时公积金*2
                    if(tUserPay.getHousebacknum()!=null){
                        float num = Float.valueOf(tUserPay.getHousebacknum())*2;
                        tUserPay.setHousebacknum(String.valueOf(num));
                    }
                    for (Field field : tUserPay.getClass().getDeclaredFields()) {
                        String MethedName = field.getName();
                        if (MethedName.contains("num") && !MethedName.equals("num")) {
                            String sumdate = ReflectionUtils.executeMethod(sumPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String itemdate = ReflectionUtils.executeMethod(tUserPay, ReflectionUtils.returnGetMethodName(MethedName)).toString();
                            String sum = String.valueOf(Float.valueOf(sumdate) + Float.valueOf(itemdate));
                            ReflectionUtils.executeSetMethod(sumPay, ReflectionUtils.returnSetMethodName(MethedName), sum);
                        }
                    }
                }

            if (tUserPays.size() > 1) {//大于1条算合计
                tUserPays.add(0, sumPay);
            }


            for (int i = 0; i < tUserPays.size(); i++) {
                tUserPays.get(i).setNum(i);
            }

            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("房山公安分局工资表");
            subheadingVo.setSheetName("在职工资表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("exusersimplepay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, tUserPays, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
    //endregion

    //region 保留津贴

    //设置扣除人员
    @RequestMapping(value = "/deptsuboutwork_user_list")
    public String UserVtdpList(Model model) {
        try {
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
        } catch (Exception ex) {
        }
        return "payassessment/deptsuboutwork_user_list";
    }


    @RequestMapping(value = "/deptsuboutwork_pay_new")
    public String PyDeptSWPayList(Model model) {
        try {
//            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            UserEntity loginUser = this.GetLoginUser();
            if (loginUser.getRealname().contains("开发")) {
                model.addAttribute("isadmin", true);
            } else {
                model.addAttribute("isadmin", false);
            }

            String username = loginUser.getUsername();
            Long orgid = loginUser.getSzdw();
            String year = getYear();
            Integer month = Integer.valueOf(getMonth());
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1){
                year =String.valueOf(Integer.valueOf(year) -1);
                quarter = 4;
            }else{
                quarter--;//默认上个季度
            }
//            String title = orglst.get(0).getOrgname().replace("&#12288;", "") + year + "年第" + quarter + "季度值勤岗位津贴、季度保留津贴及加班补贴发放表";
//            model.addAttribute("orglst", orglst);
            model.addAttribute("orgid",orgid);
//            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("status", 0);
        } catch (Exception ex) {
        }
        return "payassessment/deptsuboutwork_pay_new";
    }


    @RequestMapping(value = "/deptsuboutwork_pay_dept_new")
    public String PyDeptSWPayListDept(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntities();//按权限暂时取掉
            String year = getYear();
            Integer month = Integer.valueOf(getMonth());
            String username = this.GetLoginUser().getUsername();
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1){
                year =String.valueOf(Integer.valueOf(year) -1);
                quarter = 4;
            }else {
                quarter--;//默认上个季度
            }
//            String title = orglst.get(0).getOrgname().replace("&#12288;", "") + year + "年第" + quarter + "季度值勤岗位津贴、季度保留津贴及加班补贴发放表";
            model.addAttribute("orglst", orglst);
//            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("username", username);
            model.addAttribute("status", 1);
        } catch (Exception ex) {
        }
        return "payassessment/deptsuboutwork_pay_dept_new";
    }


    //保留津贴初始化
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_duser_list")
    public LayTable<DpUserListEntity> GetDUserList(HttpServletRequest request) {
        List<DpUserListEntity> lst = null;
        LayTable<DpUserListEntity> layTable = new LayTable<DpUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "";
            String orgs ="";

            if (orgid != null && orgid.length() > 0) {
                List<OrgEntity> orgEntities = this.GetOrgListByOrgid(Long.parseLong(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }

            }
            if (orgs.length() > 0) {
                where += " AND szdw in (" + orgs + ")";
            }


            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE realname LIKE '%" + realname + "%') ";
            }

            where += this.GetUserListByRoleForNotUser();

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;


            String limitwhere = where + " LIMIT " + beginrow + "," + endrow;

            lst = iPayAssessmentService.getDetpUserList(limitwhere);
            for (int i = 0; i < lst.size(); i++) {
                int numr = (page - 1) * limit + (i + 1);
                lst.get(i).setRownum(numr);
            }

            int iCount = iPayAssessmentService.getDetpUserCount(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @RequestMapping(value = "/deptsuboutwork_user_edit")
    public String UserVtdpEdit(Model model, Long uservtdpid) {
        try {
            String where = this.GetLoginUserForUserListWhere();
            List<UserEntity> userlst = iUserService.GetUserListByWhere("");
            model.addAttribute("userlst", userlst);

            DpUserListEntity entity = new DpUserListEntity();
            if (uservtdpid > 0) {
                entity = iPayAssessmentService.getDeptUser(uservtdpid);
            } else {
                entity.setDpuserid(0L);
            }
            model.addAttribute("entity", entity);
        } catch (Exception ex) {

        }
        return "payassessment/deptsuboutwork_user_edit";
    }

    @RequestMapping(value = "/add_dpuser")
    public String AddVtdpUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            Long uservtdpid = Long.parseLong(request.getParameter("uservtdpid"));
            String struserid = request.getParameter("userid");
            String remark = request.getParameter("remark");
            String strmoney = request.getParameter("money");
            Float money = 0f;
            if(strmoney.length()>0){
                money = Float.valueOf(strmoney);
            }


            Long userid = Long.parseLong(struserid);
            UserEntity user = this.GetUserById(userid);//拿到保存用户详细信息


            DpUserListEntity vtdpuser = new DpUserListEntity();
            vtdpuser.setUserid(userid);
            vtdpuser.setUsername(user.getRealname());
            vtdpuser.setCardno(user.getCardno());

            vtdpuser.setMoney(money);

            //固化开始
            vtdpuser.setSzdw(user.getSzdw());
            vtdpuser.setSzdwname(user.getOrgname());
            vtdpuser.setUserstatus(user.getUserstatus());
            vtdpuser.setRsgxszdw(user.getRsgxszdw());
            vtdpuser.setRsgxszdwname(user.getRsgxorgname());
            //固化结束

            UserEntity byuser = this.GetUserById(this.GetLoginUserId());
            vtdpuser.setByuserid(byuser.getUserid());
            vtdpuser.setByusername(byuser.getUsername());
            vtdpuser.setRemark(remark);

//            Date dtnow=new Date();
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//            Date dbegintime = formatter.parse(dtnow);
//            vtdpuser.setCreatetime(Date);

            int iResult = 0;
            if (uservtdpid > 0) {
                vtdpuser.setDpuserid(uservtdpid);
                iResult = iPayAssessmentService.updateDeptUserList(vtdpuser);
            } else {
                iResult = iPayAssessmentService.saveDeptUserList(vtdpuser);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    //保留津贴初始化
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_deptwork_dept_list")
    public LayTable<Map> GetOrgWorkDeptList(HttpServletRequest request) {

        List<Map> lst = null;
        LayTable<Map> layTable = new LayTable<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }


            Integer iexit = iOrgSummaryService.GetOrgYearCount("deptsub", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearDeptSubBacth(list, year);
            }

            String where = "";
            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryDeptSubList(where, year, month, "", currentmonth);

            layTable.setCode(0);
            layTable.setCount(lst.size());
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_vtdpuser")
    public ExceResult DeleteVtdpUser(HttpServletRequest request,HttpServletResponse response){
        ExceResult result=new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try{
            Long uservtdpid=Long.parseLong(request.getParameter("uservtdpid"));
            int iResult=iPayAssessmentService.deleteDeptUserList(uservtdpid);
            if(iResult>0){
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            }
            else{
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        }
        catch(Exception ex){
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_work_list")
    public GridCommon<Map> GetOrgWorkList(HttpServletRequest request) {

        List<Map> lst = null;
        GridCommon<Map> countlist = new GridCommon<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String strorgid = request.getParameter("orgid");
            String strstatus = request.getParameter("status");
            String where = "";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }


            Integer iexit = iOrgSummaryService.GetOrgYearCount("deptsub", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearDeptSubBacth(list, year);
            }
            if (this.GetOrgListByRole() != "")
                where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryDeptSubList(where, year, month, "", currentmonth);
//            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, strstatus, currentmonth);
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");
            countlist.setCountRecord(lst.size());

        } catch (Exception e) {
            e.printStackTrace();
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg(e.getMessage());
        }
        return countlist;
    }


    //补助生成
    @ResponseBody
    @RequestMapping(value = "/create_depsub_pay")
    public ExceResult CreateDepSubDetail(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        int iResult = 0;
        try {
            String strorgid = request.getParameter("orgid");
            String stryear = request.getParameter("year");
            String strmonth = request.getParameter("month");
            String[] orgids = strorgid.split(",");


            Long byuserid = this.GetLoginUserId();
            UserEntity byuser = this.GetUserById(byuserid);
            int year = Integer.parseInt(stryear);
            int month = Integer.parseInt(strmonth);
            int quarter = getquarter(month);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(year + "-" + month + "-1"));
            int countday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

            String months = getmonth(quarter);

            for (int i = 0; i < orgids.length; i++) {

                Long orgid = Long.parseLong(orgids[i]);
                Long pid = iOrgService.GetOrgById(orgid).getOrgparentid();

                AttTbBatchEntity entity = new AttTbBatchEntity();
                entity.setByuserid(byuserid);
                entity.setDay(0);
                entity.setDays(countday);
                entity.setMonth(month);//以最后一个月为季度判断
                entity.setOrgid(orgid);
                entity.setYear(year);
                entity.setQuarter(quarter);

                int iExit = iOrgSummaryService.GetExitOrgSummary(orgid, year, month, "deptsub");//每季度最后一个月代表该季
                if (iExit > 0) {
                    result.setCode(400);
                    result.setResult(iExit);
                    result.setMsg("该机构该年度该季已生成补助(" + year + "年" + quarter + "季)");
                    return result;
                }

                for (String m : months.split(",")) {
                    Integer mint = Integer.valueOf(m);
                    int isExit = iOrgSummaryService.GetExitOrgStatusSummary(orgid, year, mint, "att", "2");//是否已经归档
                    if (isExit == 0) {
                        result.setCode(400);
                        result.setResult(isExit);
                        result.setMsg(mint+"月考勤还未归档，请稍后填报！");
                        return result;
                    }
                }

                List<OrgEntity> orgEntities = new ArrayList<>();
                String orgs = "";
                String where = "";
                orgEntities = GetOrgListByOrgid(orgid);

                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }

                if (orgs.length() > 0) {
                    where += " AND szdw IN (" + orgs + ")";
                }

                List<DeptSWPayVoEntity> lst = new ArrayList<>();

                boolean novacastatus  = true;
                for (String mstr : months.split(",")) {
                    //这里循环出要统一插入的数据
                    List<UserEntity> userlst = iUserService.GetUserListWorkByWhere(where, stryear, mstr);//动态月

                    for (UserEntity userEntity : userlst) {
                        if (userEntity.getUserstatus() != null && (userEntity.getUserstatus().equals("在职")||userEntity.getUserstatus().equals("服务人员"))) {
                            DeptSWPayVoEntity voEntity = new DeptSWPayVoEntity();
                            voEntity.setMonth(mstr);//动态月
                            voEntity.setYear(stryear);
                            voEntity.setCardno(userEntity.getCardno());
                            voEntity.setUserid(userEntity.getUserid());
                            voEntity.setOrgid(userEntity.getSzdw());
                            voEntity.setRealname(userEntity.getRealname());
                            voEntity.setOrgname(userEntity.getOrgname());
                            voEntity.setUserstatus(userEntity.getUserstatus());
                            voEntity.setRsgxszdw(userEntity.getRsgxszdw());
                            voEntity.setRsgxszdwname(userEntity.getRsgxorgname());
                            Long id = userEntity.getSzdw();
                            Float nowork = userEntity.getNowork();

                            //不是服务人员
                            if(!userEntity.getUserstatus().equals("服务人员")) {
                                //政治处 ，警务保障处，纪委，巡查考核办,分局党委成员
                                if (id == 106 || id == 53 || id == 108 || id == 109 || id == 45) {
                                    Float day = 26 - nowork;
                                    day = day < 0 ? 0 : day;
                                    Float num = day * 40;
                                    voEntity.setDutynumday2(String.valueOf(day));
                                    voEntity.setDutynum2(String.valueOf(num));
                                } else {

                                    Float day = 30 - nowork;
                                    //指挥处,警务督察大队,默认设为0
                                    if (id == 107 || id == 52) {
                                        day = 0f;
                                    }
                                    day = day < 0 ? 0 : day;
                                    Float num = day * 50;
                                    voEntity.setDutynumday1(String.valueOf(day));
                                    voEntity.setDutynum1(String.valueOf(num));
                                }
                            }

                            Float Wordday = Float.valueOf(userEntity.getQqts());
                            Float noWork = userEntity.getNowork();
//                            if( Wordday > noWork) {
                                if (pid == 48L) {
                                    voEntity.setRetainnum("413");
                                } else {
                                    voEntity.setRetainnum("387");
                                }
//                            }else {
//                                voEntity.setRetainnum("0");
//                            }

                            //不是服务人员
                            if(!userEntity.getUserstatus().equals("服务人员")) {
                                if (userEntity.getSfjb() > 0f)
                                    voEntity.setOvertimenum("710");
                                else voEntity.setOvertimenum("0");
                            }
                            voEntity.setStatus(0);
                            lst.add(voEntity);
                        }
                    }
                }

//                if(novacastatus){
//                    for (WorkPayVoEntity workPayVoEntity : lst) {
//                        workPayVoEntity.setStatus(2);//直接归档
//                    }
//                    entity.setStatus(2);//直接归档
//                }

                iResult = iPayAssessmentService.createDeptSubList(entity, lst);
            }
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    @RequestMapping(value = "/deptsuboutwork_pay_dept_sh")
    public String PyDeptSWPayListDeptsh(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntities();//按权限暂时取掉
            String year = getYear();
            Integer month = Integer.valueOf(getMonth()) + 1;
            UserEntity loginUser = this.GetLoginUser();
            String username = loginUser.getRealname();
            Long orgid = loginUser.getSzdw();
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1){
                year =String.valueOf(Integer.valueOf(year) -1);
                quarter = 4;
            }
            else {
                quarter--;//默认上个季度
            }
            String title = "房山公安分局" + orglst.get(0).getOrgname().replace("&#12288;", "") + "单位" + year + "年第" + quarter + "季度补贴";
            model.addAttribute("orgid",orgid);
            model.addAttribute("title", title);
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("username", username);
            model.addAttribute("status", 1);
        } catch (Exception ex) {
        }
        return "payassessment/deptsuboutwork_pay_dept_sh";
    }


    //三合一创建（部门才能创建）
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_deptsw_list")
    public LayTable<DeptSWPaySeasonVoEntity> GetDeptSWpayList(HttpServletRequest request) {
        LayTable<DeptSWPaySeasonVoEntity> layTable = new LayTable<DeptSWPaySeasonVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            Integer quarter = Integer.valueOf(request.getParameter("quarter"));
            String orgid = request.getParameter("orgid");

            String orgs = "";
            List<OrgEntity> orgEntities = new ArrayList<>();
            orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }

            String where = "";
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarter > 0) {
                String month = getmonth(quarter);
                where += " AND month in(" + month + ")";
            }

            if (orgs.length() > 0) {
                where += " AND orgid IN (" + orgs + ")";
            }

            countWhere = where;
//            int beginrow = (page - 1) * limit * 3;
//            int endrow = limit * 3;//3月取出合计

            where +=" order by cardno,month ";
//            where += " LIMIT " + beginrow + "," + endrow;
            List<DeptSWPayVoEntity> lst = iPayAssessmentService.getDeptPayVoEntity(where);

            LinkedHashMap<String, DeptSWPaySeasonVoEntity> hashMap = new LinkedHashMap<>();
            for (DeptSWPayVoEntity swPayVoEntity : lst) {
                if (swPayVoEntity.getOrgid() != null) {//有岗位在统计
                    String cardno = swPayVoEntity.getCardno();
                    Integer month = Integer.valueOf(swPayVoEntity.getMonth());
                    Float outWork = swPayVoEntity.getOvertimenum() == null ? 0f : Float.valueOf(swPayVoEntity.getOvertimenum());
                    Float retainnum = swPayVoEntity.getRetainnum() == null ? 0f : Float.valueOf(swPayVoEntity.getRetainnum());
                    Float dutynumday1 = swPayVoEntity.getDutynumday1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday1());
                    Float dutynum1 = swPayVoEntity.getDutynum1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum1());
                    Float dutynumday2 = swPayVoEntity.getDutynumday2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday2());
                    Float dutynum2 = swPayVoEntity.getDutynum2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum2());
                    if (hashMap.containsKey(cardno)) {
                        DeptSWPaySeasonVoEntity old = hashMap.get(cardno);
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, old);

                    } else {
                        DeptSWPaySeasonVoEntity oe = new DeptSWPaySeasonVoEntity();
                        oe.setCardno(swPayVoEntity.getCardno());
                        oe.setOrgsummaryid(swPayVoEntity.getOrgsummaryid());
                        oe.setUserid(swPayVoEntity.getUserid());
                        oe.setRealname(swPayVoEntity.getRealname());
                        oe.setOrgid(swPayVoEntity.getOrgid());
                        oe.setOrgname(swPayVoEntity.getOrgname());
                        oe.setRemark(swPayVoEntity.getRemark());
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, oe);
                        oe.setMonth(swPayVoEntity.getMonth());
                        oe.setYear(swPayVoEntity.getYear());
                        oe.setStatus(swPayVoEntity.getStatus());
                        hashMap.put(cardno, oe);
                    }
                }
            }

            //全取出，聚合后翻页。
            List<DeptSWPaySeasonVoEntity> lstseason = new ArrayList<DeptSWPaySeasonVoEntity>(hashMap.values());
            List<DeptSWPaySeasonVoEntity> retrunSeason = new ArrayList<>();

            int beginrow = (page - 1) * limit;
            int endrow = limit;
            if(endrow+beginrow > lstseason.size()){
                endrow = lstseason.size();
            }else{endrow = beginrow+endrow;}
            for (int i = beginrow ;i < endrow;i++){
                retrunSeason.add(lstseason.get(i));
            }

            int iCount = lstseason.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(retrunSeason);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    private String getWorkPernum(String year, String month1, long userid) throws Exception {
        String workpernum1;
        String whereOrg = " AND userid = "+userid;
        List<UserEntity> userlst = iUserService.GetUserListWorkByWhere(whereOrg, year, month1);//动态月
        if(userlst.size()>0)
            workpernum1 = userlst.get(0).getOrgname();
        else
            workpernum1 = null;
        return workpernum1;
    }


    //部门查看页面
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_deptsw_dept_list")
    public LayTable<DeptSWPaySeasonVoEntity> GetDeptSWpayDeptList(HttpServletRequest request) {
        LayTable<DeptSWPaySeasonVoEntity> layTable = new LayTable<DeptSWPaySeasonVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            Integer quarter = Integer.valueOf(request.getParameter("quarter"));
            String strorgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");

            String where = "";
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarter > 0) {
                String month = getmonth(quarter);
                where += " AND month in(" + month + ")";
            }

            if (strorgid != null && strorgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(strorgid));
                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            countWhere = where;
//            int beginrow = (page - 1) * limit * 3;
//            int endrow = limit * 3;//3月取出合计
            where +=" order by cardno,month ";
//            where += " LIMIT " + beginrow + "," + endrow;
            List<DeptSWPayVoEntity> lst = iPayAssessmentService.getDeptPayVoEntity(where);

            String personMsg ="本季度在岗人数:";
            String outworkMsg ="加班补贴：";
            String seasonMsg = "保留津贴：";

            LinkedHashMap<String,Integer> personkey = new LinkedHashMap<>();//所含人数
            LinkedHashMap<String,Integer> servicekey = new LinkedHashMap<>();//服务人员人数
            LinkedHashMap<String, Float>  outworkkey= new LinkedHashMap<>();//验证加班补助
            LinkedHashMap<String, Float> seasonkey = new LinkedHashMap<>();//验证保留津贴

            LinkedHashMap<String, DeptSWPaySeasonVoEntity> hashMap = new LinkedHashMap<>();
            for (DeptSWPayVoEntity swPayVoEntity : lst) {
                if (swPayVoEntity.getOrgid() != null) {//有岗位在统计
                    String cardno = swPayVoEntity.getCardno();
                    Integer month = Integer.valueOf(swPayVoEntity.getMonth());
                    //计算每月人数
                    if(personkey.containsKey(month.toString())){
                        Integer value = personkey.get(month.toString())+1;
                        personkey.put(month.toString(),value);
                    }else{
                        personkey.put(month.toString(),1);
                    }

                    //计算服务人数
                    if(swPayVoEntity.getUserstatus().equals("服务人员")) {
                        if (servicekey.containsKey(month.toString())) {
                            Integer value = servicekey.get(month.toString()) + 1;
                            servicekey.put(month.toString(), value);
                        } else {
                            servicekey.put(month.toString(), 1);
                        }
                    }


                    Float outWork = swPayVoEntity.getOvertimenum() == null ? 0f : Float.valueOf(swPayVoEntity.getOvertimenum());
                    Float retainnum = swPayVoEntity.getRetainnum() == null ? 0f : Float.valueOf(swPayVoEntity.getRetainnum());
                    Float dutynumday1 = swPayVoEntity.getDutynumday1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday1());
                    Float dutynum1 = swPayVoEntity.getDutynum1() == null? 0f : Float.valueOf(swPayVoEntity.getDutynum1());
                    dutynum1 = dutynum1 < 0 ? 0f : dutynum1;
                    Float dutynumday2 = swPayVoEntity.getDutynumday2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday2());
                    Float dutynum2 = swPayVoEntity.getDutynum2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum2());

                    //保留津贴
                    if(seasonkey.containsKey(month.toString())){
                        Float value = seasonkey.get(month.toString())+retainnum;
                        seasonkey.put(month.toString(),value);
                    }else{
                        seasonkey.put(month.toString(),retainnum);
                    }

                    //加班补贴
                    if(outworkkey.containsKey(month.toString())){
                        Float value = outworkkey.get(month.toString())+outWork;
                        outworkkey.put(month.toString(),value);
                    }else{
                        outworkkey.put(month.toString(),outWork);
                    }


                    if (hashMap.containsKey(cardno)) {
                        DeptSWPaySeasonVoEntity old = hashMap.get(cardno);
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, old);

                    } else {
                        DeptSWPaySeasonVoEntity oe = new DeptSWPaySeasonVoEntity();
                        oe.setOrgsummaryid(swPayVoEntity.getOrgsummaryid());
                        oe.setCardno(swPayVoEntity.getCardno());
                        oe.setUserid(swPayVoEntity.getUserid());
                        oe.setRealname(swPayVoEntity.getRealname());
                        oe.setOrgid(swPayVoEntity.getOrgid());
                        oe.setOrgname(swPayVoEntity.getOrgname());
                        oe.setRemark(swPayVoEntity.getRemark());
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, oe);
                        oe.setMonth(swPayVoEntity.getMonth());
                        oe.setYear(swPayVoEntity.getYear());
                        oe.setStatus(swPayVoEntity.getStatus());
                        hashMap.put(cardno, oe);
                    }
                }
            }

            for (String s : personkey.keySet()) {
                personMsg += s+"月"+personkey.get(s)+"人 ";
            }
            personMsg+="\n";

            Float money = 387f;
            if (strorgid != null && strorgid.length() > 0) {
                Long pid = iOrgService.GetOrgById(Long.valueOf(strorgid)).getOrgparentid();
                if (pid == 48L) {//父级是派出所
                    money = 413f;
                }
            }
            Float sSumValue = 0f;
            Float sLeaveValue = 0f;
            for (String s : seasonkey.keySet()) {
                Float stand = personkey.get(s)*money;
                sSumValue += stand;
                Float leave = stand - seasonkey.get(s);
                sLeaveValue += leave;
                seasonMsg+=s+"月限额("+personkey.get(s)+"*"+money+"): "+stand+" 余额: "+leave+" ";
            }
            seasonMsg+="总计限额："+sSumValue+"余额："+sLeaveValue+"\n";

            Float oSumValue = 0f;
            Float oLeaveValue = 0f;
            for (String s : outworkkey.keySet()) {
                Integer servicePerson = 0;
                if(servicekey.containsKey(s)){servicePerson= servicekey.get(s);}
                Integer standPerson = personkey.get(s)-servicePerson;
                Float stand = standPerson*710f;//总额减去服务人员
                oSumValue +=stand;
                Float leave = stand - outworkkey.get(s);
                oLeaveValue += leave;
                outworkMsg+=s+"月限额("+standPerson+"*710): "+stand+" 余额: "+leave+" ";
            }
            outworkMsg+="总计限额："+oSumValue+"余额："+oLeaveValue+"\n";

            String all = personMsg+seasonMsg+outworkMsg;

            layTable.setMsg(all);
            //全取出，聚合后翻页。
            List<DeptSWPaySeasonVoEntity>  lstseason = new ArrayList<DeptSWPaySeasonVoEntity>(hashMap.values());
            List<DeptSWPaySeasonVoEntity> retrunSeason = new ArrayList<>();


            int beginrow = (page - 1) * limit;
            int endrow = limit;
            if(endrow+beginrow > lstseason.size()){
                endrow = lstseason.size();
            }else{endrow = beginrow+endrow;}
            for (int i = beginrow ;i < endrow;i++){
                retrunSeason.add(lstseason.get(i));
            }

            //处理空字段，显示为所属部门
            for (DeptSWPaySeasonVoEntity seasonlst : retrunSeason) {
                long userid = seasonlst.getUserid();
                long orgid = seasonlst.getOrgid();
                if(seasonlst.getOvertimenum1()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(1 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(orgid==106||orgid==53||orgid==108||orgid==109||orgid==45)//根据部门决定那部分（一类岗、二类岗）显示组织机构名字
                        seasonlst.setDutynum2(realOrgName);
                    else
                        seasonlst.setDutynum1(realOrgName);
                    seasonlst.setOvertimenum1(realOrgName);
                    seasonlst.setRetainnum1(realOrgName);
                }
                if(seasonlst.getOvertimenum2()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(2 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(orgid==106||orgid==53||orgid==108||orgid==109||orgid==45)
                        seasonlst.setDutynum22(realOrgName);
                    else
                        seasonlst.setDutynum12(realOrgName);
                    seasonlst.setOvertimenum2(realOrgName);
                    seasonlst.setRetainnum2(realOrgName);
                }
                if(seasonlst.getOvertimenum3()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(3 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(orgid==106||orgid==53||orgid==108||orgid==109||orgid==45)
                        seasonlst.setDutynum23(realOrgName);
                    else
                        seasonlst.setDutynum13(realOrgName);
                    seasonlst.setOvertimenum3(realOrgName);
                    seasonlst.setRetainnum3(realOrgName);
                }
            }

            int iCount =  lstseason.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(retrunSeason);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_deptsw_dept_sh_list")
    public LayTable<DeptSWPaySeasonVoEntity> GetDeptSWpayDeptSHList(HttpServletRequest request) {
        LayTable<DeptSWPaySeasonVoEntity> layTable = new LayTable<DeptSWPaySeasonVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            Integer quarter = Integer.valueOf(request.getParameter("quarter"));
            String realname = request.getParameter("realname");

            long orgid  = this.GetLoginUser().getSzdw();

            String where = " AND orgid = "+orgid;
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarter > 0) {
                String month = getmonth(quarter);
                where += " AND month in(" + month + ")";
            }

//            if (strorgid != null && strorgid.length() > 0) {
//                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(strorgid));
//                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
//                        + orgentity.getRgt() + ")";
//                where += " AND orgid = "+strorgid;
//            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            countWhere = where;
//            int beginrow = (page - 1) * limit * 3;
//            int endrow = limit * 3;//3月取出合计
            where +=" order by cardno,month ";
//            where += " LIMIT " + beginrow + "," + endrow;
            List<DeptSWPayVoEntity> lst = iPayAssessmentService.getDeptPayVoEntity(where);

            LinkedHashMap<String, DeptSWPaySeasonVoEntity> hashMap = new LinkedHashMap<>();
            for (DeptSWPayVoEntity swPayVoEntity : lst) {
                if (swPayVoEntity.getOrgid() != null) {//有岗位在统计
                    String cardno = swPayVoEntity.getCardno();
                    Integer month = Integer.valueOf(swPayVoEntity.getMonth());
                    Float outWork = swPayVoEntity.getOvertimenum() == null ? 0f : Float.valueOf(swPayVoEntity.getOvertimenum());
                    Float retainnum = swPayVoEntity.getRetainnum() == null ? 0f : Float.valueOf(swPayVoEntity.getRetainnum());
                    Float dutynumday1 = swPayVoEntity.getDutynumday1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday1());
                    Float dutynum1 = swPayVoEntity.getDutynum1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum1());
                    Float dutynumday2 = swPayVoEntity.getDutynumday2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday2());
                    Float dutynum2 = swPayVoEntity.getDutynum2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum2());
                    if (hashMap.containsKey(cardno)) {
                        DeptSWPaySeasonVoEntity old = hashMap.get(cardno);
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, old);

                    } else {
                        DeptSWPaySeasonVoEntity oe = new DeptSWPaySeasonVoEntity();
                        oe.setOrgsummaryid(swPayVoEntity.getOrgsummaryid());
                        oe.setCardno(swPayVoEntity.getCardno());
                        oe.setUserid(swPayVoEntity.getUserid());
                        oe.setRealname(swPayVoEntity.getRealname());
                        oe.setOrgid(swPayVoEntity.getOrgid());
                        oe.setOrgname(swPayVoEntity.getOrgname());
                        oe.setRemark(swPayVoEntity.getRemark());
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, oe);
                        oe.setMonth(swPayVoEntity.getMonth());
                        oe.setYear(swPayVoEntity.getYear());
                        oe.setStatus(swPayVoEntity.getStatus());
                        hashMap.put(cardno, oe);
                    }
                }
            }

            //全取出，聚合后翻页。
            List<DeptSWPaySeasonVoEntity> lstseason = new ArrayList<DeptSWPaySeasonVoEntity>(hashMap.values());
            List<DeptSWPaySeasonVoEntity> retrunSeason = new ArrayList<>();

            int beginrow = (page - 1) * limit;
            int endrow = limit;
            if(endrow+beginrow > lstseason.size()){
                endrow = lstseason.size();
            }else{endrow = beginrow+endrow;}
            for (int i = beginrow ;i < endrow;i++){
                retrunSeason.add(lstseason.get(i));
            }

            //处理空字段，显示为所属部门
            for (DeptSWPaySeasonVoEntity seasonlst : retrunSeason) {
                long userid = seasonlst.getUserid();
                long rorgid = seasonlst.getOrgid();
                if(seasonlst.getOvertimenum1()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(1 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)//根据部门决定那部分（一类岗、二类岗）显示组织机构名字
                        seasonlst.setDutynum2(realOrgName);
                    else
                        seasonlst.setDutynum1(realOrgName);
                    seasonlst.setOvertimenum1(realOrgName);
                    seasonlst.setRetainnum1(realOrgName);
                }
                if(seasonlst.getOvertimenum2()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(2 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)
                        seasonlst.setDutynum22(realOrgName);
                    else
                        seasonlst.setDutynum12(realOrgName);
                    seasonlst.setOvertimenum2(realOrgName);
                    seasonlst.setRetainnum2(realOrgName);
                }
                if(seasonlst.getOvertimenum3()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(3 +(quarter-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)
                        seasonlst.setDutynum23(realOrgName);
                    else
                        seasonlst.setDutynum13(realOrgName);
                    seasonlst.setOvertimenum3(realOrgName);
                    seasonlst.setRetainnum3(realOrgName);
                }
            }

            int iCount = lstseason.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(retrunSeason);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    //3合1保存
    @RequestMapping(value = "/deptsw_pay_save", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult DeptSWPaySave(@RequestBody DeptSWSeasonPayList uatmzpdsummary) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            List<DeptSWPaySeasonVoEntity> payVoEntities = uatmzpdsummary.getVtdpuserlist();
            List<DeptSWPaySeasonVoEntity> saveVoList = new ArrayList<>();
            List<DeptSWPayVoEntity> voEntities = new ArrayList<>();
            String year = uatmzpdsummary.getYear();
            Integer quarter = Integer.valueOf(uatmzpdsummary.getQuarter());
            String userid = "";
            String where = "";

            //取出部门下所有人
            Long orgid = payVoEntities.get(0).getOrgid();
            String orgname = payVoEntities.get(0).getOrgname();
            Long pid = iOrgService.GetOrgById(orgid).getOrgparentid();

            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarter > 0) {
                String month = getmonth(quarter);
                where += " AND month in(" + month + ")";
            }

            if (orgid > 0) {
                where += " AND orgid IN (" + orgid + ")";
            }


            List<DeptSWPayVoEntity> allPayVo = iPayAssessmentService.getDeptPayVoEntity(where);


            //统一保存
            Integer status = payVoEntities.get(0).getStatus();
            if (status == null || status == 0 || status == 4||status == 5){
                for (DeptSWPaySeasonVoEntity payVoEntity : payVoEntities) {
                    saveVoList.add(payVoEntity);
                }
            }else {
                result.setCode(300);
                result.setResult(-1);
                result.setMsg("该状态无法更新");
                return  result;
            }

            int iResult = -1;
            if (saveVoList.size() > 0) {
                userid = new SeasonToItem(saveVoList, year, quarter, userid, voEntities).invoke();

                Map<String, Float> menykey = new HashMap<>();
                Map<String, Float> saveKey = new HashMap<>();
                for (DeptSWPayVoEntity payVoEntity : voEntities) {
                    float overtimenum = 0.0f;
                    float retainnum = 0.0f;
                    if (payVoEntity.getOvertimenum() != null&&isNumberd(payVoEntity.getOvertimenum()))
                        overtimenum = Float.valueOf(payVoEntity.getOvertimenum());
                    if(payVoEntity.getRetainnum() != null&&isNumberd(payVoEntity.getRetainnum()))
                        retainnum = Float.valueOf(payVoEntity.getRetainnum());
                    menykey.put(payVoEntity.getMonth() + payVoEntity.getUserid(), overtimenum);
                    saveKey.put(payVoEntity.getMonth() + payVoEntity.getUserid(), retainnum);
                }


                Map<String, Float> menymonthkey = new HashMap<>();//验证加班补助
                Map<String, Float> menysavekey = new HashMap<>();//验证保留津贴
                Map<String, Float>personkey = new HashMap<>();//每月人数
                Map<String, Float>servicekey = new HashMap<>();//每月服务人员人数

                for (DeptSWPayVoEntity voEntity : allPayVo) {

                    //计算每月人数
                    Integer month = Integer.valueOf(voEntity.getMonth());
                    if(personkey.containsKey(month.toString())){
                        Float value = personkey.get(month.toString())+1f;
                        personkey.put(month.toString(),value);
                    }else{
                        personkey.put(month.toString(),1f);
                    }
                    //计算每月服务人数
                    if(voEntity.getUserstatus().equals("服务人员")){
                        if(servicekey.containsKey(month.toString())){
                            Float value = servicekey.get(month.toString())+1f;
                            servicekey.put(month.toString(),value);
                        }else{
                            servicekey.put(month.toString(),1f);
                        }
                    }

                    String key = voEntity.getMonth();
                    String pkey = voEntity.getMonth() + voEntity.getUserid();


                    if(voEntity.getOvertimenum()!=null && isNumberd(voEntity.getOvertimenum())){
                    if (menymonthkey.containsKey(key)) {//保存值替换
                        Float sum = 0f;
                        if (menykey.containsKey(pkey)) {
                            sum = menykey.get(pkey);
                        } else {
                            sum = Float.valueOf(voEntity.getOvertimenum());
                        }
                        Float old = menymonthkey.get(key);
                        menymonthkey.put(key, sum + old);
                    } else {
                        Float sum = 0f;
                        if (menykey.containsKey(pkey)) {//保存值替换
                            sum = menykey.get(pkey);
                        } else {
                            sum = Float.valueOf(voEntity.getOvertimenum());
                        }
                        menymonthkey.put(key, sum);
                    }
                    }
                    if(voEntity.getRetainnum()!=null && isNumberd(voEntity.getRetainnum())) {
                        if (menysavekey.containsKey(key)) {//保存值替换
                            Float sum = 0f;
                            if (saveKey.containsKey(pkey)) {
                                sum = saveKey.get(pkey);
                            } else {
                                sum = Float.valueOf(voEntity.getRetainnum());
                            }
                            Float old = menysavekey.get(key);
                            menysavekey.put(key, sum + old);
                        } else {
                            Float sum = 0f;
                            if (saveKey.containsKey(pkey)) {//保存值替换
                                sum = saveKey.get(pkey);
                            } else {
                                sum = Float.valueOf(voEntity.getRetainnum());
                            }
                            menysavekey.put(key, sum);
                        }
                    }
                }

                boolean isout = false;
                boolean isoutdata = false;
                LinkedHashMap<String, Float>  outworkkey= new LinkedHashMap<>();//验证加班补助
                LinkedHashMap<String, Float> seasonkey = new LinkedHashMap<>();//验证保留津贴

                for (String s : personkey.keySet()) {
                    float servicePerson = 0f;
                    if(servicekey.containsKey(s)){servicePerson= servicekey.get(s);}
                    Float standSum = (personkey.get(s)-servicePerson)*710f;//总额减去服务人员
                    outworkkey.put(s,standSum);
                }

                //不再每个月判断
//                for (String s : menymonthkey.keySet()) {
//                    if (menymonthkey.get(s) > outworkkey.get(s)) {
//                        isout = true;
//                        isoutdata = true;
//                    }
//                }
                //改为总额判断是否超标
                Float ostand = 0f;
                Float oout = 0f;
                for (String s : menymonthkey.keySet()) {
                    ostand += outworkkey.get(s);
                    oout += menymonthkey.get(s);
                }
                if (oout > ostand) {
                        isout = true;
                        isoutdata = true;
                }

                Float money = 0f;
                boolean issavemoney = false;
                if (pid == 48L) {//父级是派出所
                    money = 413f;
                } else {
                    money = 387f;
                }

                for (String s : personkey.keySet()) {
                    Float standSum = personkey.get(s)*money;
                    seasonkey.put(s,standSum);
                }

                //按月判断
//                for (String s : menysavekey.keySet()) {
//                    if (menysavekey.get(s) > seasonkey.get(s)){
//                        isout = true;
//                        issavemoney = true;
//                    }
//                }
                Float sstand = 0f;
                Float sout = 0f;
                for (String s : menysavekey.keySet()) {
                    sstand += seasonkey.get(s);
                    sout += menysavekey.get(s);
                }
                if (sout > sstand) {
                    isout = true;
                    issavemoney = true;
                }

                if (!isout) {
                    iResult = iPayAssessmentService.updateDeptPayList(voEntities);
                    if (iResult > 0) {
                        result.setCode(200);
                        result.setResult(iResult);
                        result.setMsg("操作成功");
                    } else {
                        result.setCode(300);
                        result.setResult(iResult);
                        result.setMsg("操作失败");
                    }
                } else {
                    String msg = "总额已超标";
                    if (isoutdata) msg = "加班补助已经超标";
                    if (issavemoney) msg = "保留津贴已经超标";
                    result.setCode(300);
                    result.setResult(iResult);
                    result.setMsg(msg);
                }

            }
        }catch (Exception e) {
            result.setCode(500);
            result.setResult(-1);
            if(e.getMessage().equals("empty String")){
                result.setMsg("请填写");
            }else {
                result.setMsg("操作失败");
            }
        }
        return result;
    }


public boolean isNumberd(String str){
    for (int i = 0; i < str.length(); i++)
    {
         if(str.charAt(i)=='.') continue;
        if (!Character.isDigit(str.charAt(i)))
        {
            return false;
        }
    }
    return true;
}


    //update_work_pay状态改变
    @RequestMapping(value = "/deptsw_pay_update_status", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult DeptSWPayUpdateStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long orgsummaryid = Long.valueOf(request.getParameter("orgsummaryid"));
            Integer status = Integer.valueOf(request.getParameter("status"));

            int iResult = 0;
            iResult = iPayAssessmentService.UpdateDeptSubAttStatus(orgsummaryid, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    //update_work_pay状态改变
    @RequestMapping(value = "/deptsw_pay_update_statusbm", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult DeptSWPayUpdateStatusbm(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String orgsummaryids = request.getParameter("orgsummaryids");
            Integer status = Integer.valueOf(request.getParameter("status"));
            String where = "";

            if(orgsummaryids!=null||orgsummaryids.length()>0){
                where = "AND orgsummaryid IN (" + orgsummaryids + ")";
            }


            int iResult = 0;

            if(!where.equals(""))
                iResult = iPayAssessmentService.UpdateDeptSubAttStatusWhere(where, status);

            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    //3合1状态改变
    @RequestMapping(value = "/deptsw_pay_update", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult DeptSWPayUpdate(@RequestBody DeptSWSeasonPayList uatmzpdsummary) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
        List<DeptSWPaySeasonVoEntity> payVoEntities = uatmzpdsummary.getVtdpuserlist();
        List<DeptSWPaySeasonVoEntity> saveVoList = new ArrayList<>();
        Integer status = Integer.valueOf(uatmzpdsummary.getStatus());
        Long orgsummaryid = payVoEntities.get(0).getOrgsummaryid();
        int iResult = 0;
        iResult = iPayAssessmentService.UpdateDeptSubAttStatus(orgsummaryid, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex){
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/createPDF")
    public int uploadBillClient(HttpServletRequest request) {

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码

            byte[] b = decoder.decodeBuffer(request.getParameter("file"));
            String year = request.getParameter("year");
            String month = request.getParameter("quarter");//根据季度来拿，对的
            String orgid = this.GetLoginUser().getSzdw().toString();
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            String fileName = "deptpay/" + year + "/" + month + "/" + orgid + "/file.pdf";
            String filePath = "/Users/lizeze/Desktop/a/pdf/";


            filePath = ConfigOption.getInstance().getFileurl() + "/pdf/";
            fileName = filePath + fileName;


            File file = new File(fileName);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            OutputStream out = new FileOutputStream(fileName);
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return 0;
        }
        return 1;
    }


    @ResponseBody
    @RequestMapping(value = "/showPDF")
    public String lookPdf(HttpServletRequest request) {
        try {
            List<Configure> configureList = new ArrayList<>();
            configureList = configureService.getAll(" and  code='31dept'");

            if (configureList.size() > 0) {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  ");
                Configure configure = configureList.get(0);

                Date start = sdf.parse(sdf.format(configure.getStarttime()));
                Date end = sdf.parse(sdf.format(configure.getEndtime()));
                Date now = sdf.parse(sdf.format(d));
                //去掉公式时间验证
//                String yeartr = request.getParameter("year");
//                String monthtr = request.getParameter("month");
//                    int year = Integer.parseInt(yeartr);
//                    int month = Integer.parseInt(monthtr);


                    Calendar cal = Calendar.getInstance();
                    int currentyear = cal.get(Calendar.YEAR);
                    int currentmonth = cal.get(Calendar.MONTH) + 1;
//                    if (currentyear != year) {
//                        currentmonth = 12;
//                    }
                    Integer searchmonth =0;
                    Integer quarter = 0;
                    if (currentmonth == 1 || currentmonth == 2 || currentmonth == 3) {
                        currentyear=currentyear-1;
                        quarter = 4;
                        searchmonth =10;
                    }
                    if (currentmonth == 4 || currentmonth == 5 || currentmonth == 6) {
                        quarter = 1;
                        searchmonth = 1;
                    }
                    if (currentmonth == 7 || currentmonth == 8 || currentmonth == 9) {
                        quarter = 2;
                        searchmonth = 4;
                    }
                    if (currentmonth == 10 || currentmonth == 11 || currentmonth == 12) {
                        quarter = 3;
                        searchmonth = 7;
                    }

                    String where = "";
                    where += " AND orgid IN (" + this.GetLoginUser().getSzdw() + ")";

                    where += "AND status = 2 AND year = "+currentyear+" AND month = "+searchmonth;


                    int count = iPayAssessmentService.getDeptPayVoEntityCount(where);

                    if (count > 0) {

                        String webUrl = "http://127.0.0.1:8081/";
                        webUrl = ConfigOption.getInstance().getWeburl();
                        return webUrl + "pdf/deptpay/" + currentyear + "/" + quarter + "/" + this.GetLoginUser().getSzdw() + "/file.pdf";

                    }
            }


        } catch (Exception ex) {

        }

        return "";
    }


    @RequestMapping(value = "/deptsuboutwork_pay_look")
    public String lookPDf(Model model) {
        try {


        } catch (Exception ex) {

        }
        return "payassessment/deptsuboutwork_pay_look";
    }

    @ResponseBody
    @RequestMapping(value = "/deptsw_pay_export")
    public ExceResult deptExportExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String quarter = request.getParameter("quarter");
            Integer qua = Integer.valueOf(quarter);
            String orgid = request.getParameter("orgid");
            String where = "";

            String monthstr = getmonth(qua);

            if (orgid != null && orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (monthstr != null && monthstr.length() > 0) {
                where += " AND month in (" + monthstr + ")";
            }

            List<DeptSWPayVoEntity> lst = iPayAssessmentService.getDeptPayVoEntity(where);

            LinkedHashMap<String, DeptSWPaySeasonVoEntity> hashMap = new LinkedHashMap<>();
            for (DeptSWPayVoEntity swPayVoEntity : lst) {
                if (swPayVoEntity.getOrgid() != null) {//有岗位在统计
                    String cardnokey = swPayVoEntity.getCardno()+swPayVoEntity.getOrgid();
                    Integer month = Integer.valueOf(swPayVoEntity.getMonth());
                    Float outWork = swPayVoEntity.getOvertimenum() == null ? 0f : Float.valueOf(swPayVoEntity.getOvertimenum());
                    Float retainnum = swPayVoEntity.getRetainnum() == null ? 0f : Float.valueOf(swPayVoEntity.getRetainnum());
                    Float dutynumday1 = swPayVoEntity.getDutynumday1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday1());
                    Float dutynum1 = swPayVoEntity.getDutynum1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum1());
                    Float dutynumday2 = swPayVoEntity.getDutynumday2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday2());
                    Float dutynum2 = swPayVoEntity.getDutynum2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum2());
                    if (hashMap.containsKey(cardnokey)) {
                        DeptSWPaySeasonVoEntity old = hashMap.get(cardnokey);
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, old);//老的累计

                    } else {
                        DeptSWPaySeasonVoEntity oe = new DeptSWPaySeasonVoEntity();//新的新建
                        oe.setCardno(swPayVoEntity.getCardno());
                        oe.setUserid(swPayVoEntity.getUserid());
                        oe.setRealname(swPayVoEntity.getRealname());
                        oe.setOrgid(swPayVoEntity.getOrgid());
                        oe.setOrgname(swPayVoEntity.getOrgname());
                        oe.setRemark(swPayVoEntity.getRemark());
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, oe);
                        oe.setMonth(swPayVoEntity.getMonth());
                        oe.setYear(swPayVoEntity.getYear());
                        oe.setStatus(swPayVoEntity.getStatus());
                        hashMap.put(cardnokey, oe);
                    }
                }
            }

            List<DeptSWPaySeasonVoEntity> lstseason = new ArrayList<DeptSWPaySeasonVoEntity>(hashMap.values());
            Collections.sort(lstseason, new Comparator<DeptSWPaySeasonVoEntity>(){
                /*
                 * int compare(Person p1, Person p2) 返回一个基本类型的整型，
                 * 返回负数表示：p1 小于p2，
                 * 返回0 表示：p1和p2相等，
                 * 返回正数表示：p1大于p2
                 */
                public int compare(DeptSWPaySeasonVoEntity p1, DeptSWPaySeasonVoEntity p2) {
                    //按照orgid进行升序排列
                    if(p1.getOrgid() > p2.getOrgid()){
                        return 1;
                    }
                    if(p1.getOrgid() == p2.getOrgid()){
                        return 0;
                    }
                    return -1;
                }
            });

            for (int i = 0; i < lstseason.size(); i++) {
                lstseason.get(i).setRowNum(i + 1);
            }

            //处理空字段，显示为所属部门
            for (DeptSWPaySeasonVoEntity seasonlst : lstseason) {
                long userid = seasonlst.getUserid();
                long rorgid = seasonlst.getOrgid();
                if(seasonlst.getOvertimenum1()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(1 +(qua-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)//根据部门决定那部分（一类岗、二类岗）显示组织机构名字
                        seasonlst.setDutynum2(realOrgName);
                    else
                        seasonlst.setDutynum1(realOrgName);
                    seasonlst.setOvertimenum1(realOrgName);
                    seasonlst.setRetainnum1(realOrgName);
                }
                if(seasonlst.getOvertimenum2()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(2 +(qua-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)
                        seasonlst.setDutynum22(realOrgName);
                    else
                        seasonlst.setDutynum12(realOrgName);
                    seasonlst.setOvertimenum2(realOrgName);
                    seasonlst.setRetainnum2(realOrgName);
                }
                if(seasonlst.getOvertimenum3()==null){//没有，就显示真实所在部门。
                    String month = String.valueOf(3 +(qua-1)*3);
                    String realOrgName = getWorkPernum(year, month, userid);
                    if(rorgid==106||rorgid==53||rorgid==108||rorgid==109||rorgid==45)
                        seasonlst.setDutynum23(realOrgName);
                    else
                        seasonlst.setDutynum13(realOrgName);
                    seasonlst.setOvertimenum3(realOrgName);
                    seasonlst.setRetainnum3(realOrgName);
                }
            }


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


            String fileName = "31butie_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("津贴补助表");
            subheadingVo.setSheetName("第"+quarter+"季在职补助表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("deptsubpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, lstseason, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);

        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/deptsw_export_all")
    public ExceResult deptExportall(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String quarter = request.getParameter("quarter");
            Integer qua = Integer.valueOf(quarter);
            String orgid = request.getParameter("orgid");
            String where = "";

            String monthstr = getmonth(qua);
//全部导出去掉部门
//            if (orgid != null && orgid.length() > 0) {
//                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
//                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
//                        + orgentity.getRgt() + ")";
//            }

            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (monthstr != null && monthstr.length() > 0) {
                where += " AND month in (" + monthstr + ")";
            }

            List<DeptSWPayVoEntity> lst = iPayAssessmentService.getDeptPayVoEntity(where);

            LinkedHashMap<String, DeptSWPaySeasonVoEntity> hashMap = new LinkedHashMap<>();
            for (DeptSWPayVoEntity swPayVoEntity : lst) {
                if (swPayVoEntity.getOrgid() != null) {//有岗位在统计
                    //String cardnokey = swPayVoEntity.getCardno()+swPayVoEntity.getOrgid();
                    String cardnokey = swPayVoEntity.getCardno();//根据人员分组，不再考虑部门
                    Integer month = Integer.valueOf(swPayVoEntity.getMonth());
                    Float outWork = swPayVoEntity.getOvertimenum() == null ? 0f : Float.valueOf(swPayVoEntity.getOvertimenum());
                    Float retainnum =swPayVoEntity.getRetainnum() == null ? 0f : Float.valueOf(swPayVoEntity.getRetainnum());
                    Float dutynumday1 = swPayVoEntity.getDutynumday1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday1());
                    Float dutynum1 = swPayVoEntity.getDutynum1() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum1());
                    Float dutynumday2 = swPayVoEntity.getDutynumday2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynumday2());
                    Float dutynum2 = swPayVoEntity.getDutynum2() == null ? 0f : Float.valueOf(swPayVoEntity.getDutynum2());
                    if (hashMap.containsKey(cardnokey)) {
                        DeptSWPaySeasonVoEntity old = hashMap.get(cardnokey);
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, old);//老的累计
                    } else {
                        DeptSWPaySeasonVoEntity oe = new DeptSWPaySeasonVoEntity();//新的新建
                        oe.setCardno(swPayVoEntity.getCardno());
                        oe.setUserid(swPayVoEntity.getUserid());
                        oe.setRealname(swPayVoEntity.getRealname());
                        oe.setOrgid(swPayVoEntity.getOrgid());
                        oe.setOrgname(swPayVoEntity.getOrgname());
                        oe.setRemark(swPayVoEntity.getRemark());
                        setDeptSWdata(month, outWork, retainnum, dutynumday1, dutynum1, dutynumday2, dutynum2, oe);
                        oe.setMonth(swPayVoEntity.getMonth());
                        oe.setYear(swPayVoEntity.getYear());
                        oe.setStatus(swPayVoEntity.getStatus());
                        hashMap.put(cardnokey, oe);
                    }
                }
            }

            List<DeptSWPaySeasonVoEntity> lstseason = new ArrayList<DeptSWPaySeasonVoEntity>(hashMap.values());
            Collections.sort(lstseason, new Comparator<DeptSWPaySeasonVoEntity>(){
                /*
                 * int compare(Person p1, Person p2) 返回一个基本类型的整型，
                 * 返回负数表示：p1 小于p2，
                 * 返回0 表示：p1和p2相等，
                 * 返回正数表示：p1大于p2
                 */
                public int compare(DeptSWPaySeasonVoEntity p1, DeptSWPaySeasonVoEntity p2) {
                    //按照orgid进行升序排列
                    if(p1.getOrgid() > p2.getOrgid()){
                        return 1;
                    }
                    if(p1.getOrgid() == p2.getOrgid()){
                        return 0;
                    }
                    return -1;
                }
            });

            for (int i = 0; i < lstseason.size(); i++) {
                lstseason.get(i).setRowNum(i + 1);
            }


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "31butie_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("津贴补助表");
            subheadingVo.setSheetName("第"+quarter+"季在职补助表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("deptsubpayall.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, lstseason, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);

        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }




    private void setDeptSWdata(Integer month, Float outWork, Float retainnum, Float dutynumday1, Float dutynum1, Float dutynumday2, Float dutynum2, DeptSWPaySeasonVoEntity oe) {
        Float overTime = 0f;
        if(oe.getOvertimenumsum()!=null)overTime=Float.valueOf(oe.getOvertimenumsum());
        Float retain = 0f;
        if(oe.getRetainnumsum()!=null)retain=Float.valueOf(oe.getRetainnumsum());
        Float duty = 0f;
        if(oe.getDutynumsum()!=null)duty = Float.valueOf(oe.getDutynumsum());

        if (month == 1 || month == 4 || month == 7 || month == 10) {
            if (dutynum1 > 0) {
                oe.setDutynum1(String.valueOf(dutynum1));
                oe.setDutynumday1(String.valueOf(dutynumday1));
            }
            if (dutynum2 > 0) {
                oe.setDutynum2(String.valueOf(dutynum2));
                oe.setDutynumday2(String.valueOf(dutynumday2));
            }
            oe.setRetainnum1(String.valueOf(retainnum));
            oe.setOvertimenum1(String.valueOf(outWork));
        }
        if (month == 2 || month == 5 || month == 8 || month == 11) {
            if (dutynum1 > 0) {
                oe.setDutynum12(String.valueOf(dutynum1));
                oe.setDutynumday12(String.valueOf(dutynumday1));
            }
            if (dutynum2 > 0) {
                oe.setDutynum22(String.valueOf(dutynum2));
                oe.setDutynumday22(String.valueOf(dutynumday2));
            }
            oe.setRetainnum2(String.valueOf(retainnum));
            oe.setOvertimenum2(String.valueOf(outWork));
        }
        if (month == 3 || month == 6 || month == 9 || month == 12) {
            if (dutynum1 > 0) {
                oe.setDutynum13(String.valueOf(dutynum1));
                oe.setDutynumday13(String.valueOf(dutynumday1));
            }
            if (dutynum2 > 0) {
                oe.setDutynum23(String.valueOf(dutynum2));
                oe.setDutynumday23(String.valueOf(dutynumday2));
            }
            oe.setRetainnum3(String.valueOf(retainnum));
            oe.setOvertimenum3(String.valueOf(outWork));
        }
        //合计拿出
        oe.setDutynumsum(String.valueOf(dutynum1 + dutynum2+duty));//值勤岗位津贴合计
        oe.setOvertimenumsum(String.valueOf(outWork + overTime ));//加班补贴合计
        oe.setRetainnumsum(String.valueOf(retain + retainnum));//保留津贴合计
        oe.setSummoney(retainnum + outWork+ dutynum1+ dutynum2 + oe.getSummoney());//合计
    }
    //endregion

    //region 汇总查看

    //获取组织机构
    @RequestMapping(value = "/outwork_pay_season_list")
    public String outworkPayList(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntities();//按权限暂时取掉
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1){
                year =year -1;
                quarter = 4;
            }
            else {
                quarter--;//默认上个季度
            }
            String title = year + "年第" + quarter + "季度加班补贴发放情况";
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("orglst", orglst);
            model.addAttribute("title", title);
        } catch (Exception ex) {

        }
        return "payassessment/outwork_pay_season_list";
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_outwork_season_list")
    public LayTable<outWorkVoEntity> GetoutworkList(HttpServletRequest request) {
        List<outWorkVoEntity> lst = null;
        LayTable<outWorkVoEntity> layTable = new LayTable<outWorkVoEntity>();
        try {
            String year = request.getParameter("year");
            int quarter = Integer.parseInt(request.getParameter("quarter"));
            String strorgid = request.getParameter("orgid");
            String where = "";
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarter > 0) {
                String month = getmonth(quarter);
                where += " AND month in(" + month + ")";
            }

            String orgs = "";
            List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(strorgid));

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }

            if (orgs.length() > 0) {
                where += " AND orgid in (" + orgs + ")";
            }

            List<outWorkEntity> orilist = iPayAssessmentService.getOutWork(where);

            LinkedHashMap<String, outWorkVoEntity> hashMap = new LinkedHashMap<>();
            for (outWorkEntity outWorkEntity : orilist) {
                if (outWorkEntity.getOrgid() != null) {//有岗位在统计
                    String orgid = String.valueOf(outWorkEntity.getOrgid());
                    Integer month = Integer.valueOf(outWorkEntity.getMonth());
                    Float outWork = Float.valueOf(outWorkEntity.getOvertimenum());
                    if (hashMap.containsKey(orgid)) {
                        outWorkVoEntity old = hashMap.get(orgid);
                        if (month == old.getMonth1()) {
                            old.setMonthmoney1(outWork + old.getMonthmoney1());
                            old.setMonthperson1(old.getMonthperson1() + 1);
                        } else if (old.getMonth2() == 0 || month == old.getMonth2()) {
                            old.setMonth2(month);
                            old.setMonthmoney2(outWork + old.getMonthmoney2());
                            old.setMonthperson2(old.getMonthperson2() + 1);

                        } else {
                            old.setMonth3(month);
                            old.setMonthmoney3(outWork + old.getMonthmoney3());
                            old.setMonthperson3(old.getMonthperson3() + 1);
                        }

                    } else {
                        outWorkVoEntity oe = new outWorkVoEntity();
                        oe.setOrgname(outWorkEntity.getOrgname());
                        oe.setMonth1(month);
                        oe.setMonthmoney1(outWork);
                        oe.setMonthperson1(oe.getMonthperson1() + 1);
                        hashMap.put(orgid, oe);
                    }
                }
            }

            lst = new ArrayList<outWorkVoEntity>(hashMap.values());

            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRownum(i + 1);
            }

            int iCount = lst.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/export_season_outwork", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult exportseasonoutworkExcel(@RequestBody outWorkVoEntityList outWorkVoEntityList) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            List<outWorkVoEntity> outWorkVoEntities = outWorkVoEntityList.getUatmzpdsummary();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


            String fileName = "jiabanbutie_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("加班补贴表");
            subheadingVo.setSheetName("加班补贴表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("outworkpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, outWorkVoEntities, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //获取组织机构
    @RequestMapping(value = "/work_pay_season_list")
    public String workPaySeanList(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntities();//按权限暂时取掉
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1){
                year =year -1;
                quarter = 4;
            }
            else {
                quarter--;//默认上个季度
            }
            String title = orglst.get(0).getOrgname() + "(" + year + "年第" + quarter + "季度)工作性津贴申报表";
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("orglst", orglst);
            model.addAttribute("title", title);
        } catch (Exception ex) {

        }
        return "payassessment/work_pay_season_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_work_season_list")
    public LayTable<WorkSeanVoEntity> GetworkSeanList(HttpServletRequest request) {
        List<WorkPayVoEntity> orilist = null;
        LayTable<WorkSeanVoEntity> layTable = new LayTable<WorkSeanVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String quarter = request.getParameter("quarter");
            int quarterInt = Integer.parseInt(quarter);
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");

            String month1 = "";
            String month2 = "";
            String month3 = "";

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if(month == null||month.equals("")){
                month = getLastMonth(quarterInt);
            }


            if (quarterInt > 0) {
                String[] months = getmonth(quarterInt).split(",");
                month1 = months[0];
                month2 = months[1];
                month3 = months[2];
            }

            if (orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String whereLimit = " LIMIT " + beginrow + "," + endrow;
            List<WorkSeanVoEntity> lst = iPayAssessmentService.getWorkSeanPayEntiy(where, whereLimit, month1, month2, month3, month);
            for (int i = 0; i < lst.size(); i++) {
                int rownum = (page - 1) * limit + (i + 1);
                lst.get(i).setRownum(rownum);
                String workpernum1 = lst.get(i).getWorkpernum1();
                String workpernum2 = lst.get(i).getWorkpernum2();
                String workpernum3 = lst.get(i).getWorkpernum3();
                Float downsum = 0f;
                if (workpernum1 != null && !workpernum1.equals("")) downsum += Float.valueOf(workpernum1);
                if (workpernum2 != null && !workpernum2.equals("")) downsum += Float.valueOf(workpernum2);
                if (workpernum3 != null && !workpernum3.equals("")) downsum += Float.valueOf(workpernum3);

                downsum = 0 -downsum;
                if(downsum != 0){
                    if(lst.get(i).getDownreason()==null||lst.get(i).getDownreason().equals("")){
                        lst.get(i).setDownreason("根据考勤情况扣减");
                    }
                }
                //不是钱合计，而是减扣金额合计
                lst.get(i).setWorkpernumsum(downsum.toString());
            }

            List<WorkSeanVoEntity> lstcount = iPayAssessmentService.getWorkSeanPayEntiy(where, "", month1, month2, month3, month);
            int iCount = lstcount.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/export_excel")
    public ExceResult ExportExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String quarter = request.getParameter("quarter");
            int quarterInt = Integer.parseInt(quarter);
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");


            String month1 = "";
            String month2 = "";
            String month3 = "";

            String where = "";

            if(month == null){
                month = getLastMonth(quarterInt);
            }

            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (quarterInt > 0) {
                String[] months = getmonth(quarterInt).split(",");
                month1 = months[0];
                month2 = months[1];
                month3 = months[2];
            }

            if (orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND orgid IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            List<WorkSeanVoEntity> lst = iPayAssessmentService.getWorkSeanPayEntiy(where, "", month1, month2, month3, month);
            for (int i = 0; i < lst.size(); i++) {
                int rownum = i + 1;
                lst.get(i).setRownum(rownum);
                String workpernum1 = lst.get(i).getWorkpernum1();
                String workpernum2 = lst.get(i).getWorkpernum2();
                String workpernum3 = lst.get(i).getWorkpernum3();
                Float downsum = 0f;
                if (workpernum1 != null && !workpernum1.equals("")) downsum += Float.valueOf(workpernum1);
                if (workpernum2 != null && !workpernum2.equals("")) downsum += Float.valueOf(workpernum2);
                if (workpernum3 != null && !workpernum3.equals("")) downsum += Float.valueOf(workpernum3);
                downsum = 0 - downsum;

                lst.get(i).setWorkpernumsum(downsum.toString());
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String orgName = lst.get(0).getOrgname();

            String fileName = "jingtie_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("房山市分局"+orgName+"部门第"+quarterInt+"季津贴补助表");
            subheadingVo.setSheetName("在职补助表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("workpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, lst, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);

        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }



    //endregion

    //region 公共类

    public static String getSavePath(String url) {
//        todo:最好动态获取，改为动态的路径
        String savePath = url + "/" + getYear() + "/" + getMonth() + "/" + getDay() + "/";
        File dirPath = new File(savePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        return savePath;
    }

    private String getmonth(Integer sqn) {
        String ret = "";
        switch (sqn) {
            case 1:
                ret = "1,2,3";
                break;
            case 2:
                ret = "4,5,6";
                break;
            case 3:
                ret = "7,8,9";
                break;
            case 4:
                ret = "10,11,12";
                break;
        }
        return ret;
    }

    private Integer getquarter(int month) {
        int quarter = 1;
        switch (month) {
            case 1:
            case 2:
            case 3:
                quarter = 1;
                break;
            case 4:
            case 5:
            case 6:
                quarter = 2;
                break;
            case 7:
            case 8:
            case 9:
                quarter = 3;
                break;
            case 10:
            case 11:
            case 12:
                quarter = 4;
                break;
        }
        return quarter;
    }


    private class SeasonToItem {
        private List<DeptSWPaySeasonVoEntity> payVoEntities;
        private String year;
        private Integer quarter;
        private String userid;
        private List<DeptSWPayVoEntity> voEntities;

        public SeasonToItem(List<DeptSWPaySeasonVoEntity> payVoEntities, String year, Integer quarter, String userid, List<DeptSWPayVoEntity> voEntities) {
            this.payVoEntities = payVoEntities;
            this.year = year;
            this.quarter = quarter;
            this.userid = userid;
            this.voEntities = voEntities;
        }

        public String invoke() {
            for (DeptSWPaySeasonVoEntity payVo : payVoEntities) {
                for (int i = 0; i < 3; i++) {
                    DeptSWPayVoEntity vo = new DeptSWPayVoEntity();
                    vo.setCardno(payVo.getCardno());
                    vo.setUserid(payVo.getUserid());
                    vo.setRealname(payVo.getRealname());
                    vo.setOrgid(payVo.getOrgid());
                    vo.setOrgname(payVo.getOrgname());
//                    vo.setDutynum(String.valueOf(Float.valueOf(payVo.getDutynum1())+Float.valueOf(payVo.getDutynum2())));
                    vo.setDutynum("0");//todo:修改
                    vo.setRemark(payVo.getRemark());
                    vo.setStatus(payVo.getStatus());
                    vo.setYear(year);
                    if (quarter == 1) {
                        if (i == 0) {
                            vo.setMonth("1");
                            vo.setDutynum1(payVo.getDutynum1());
                            vo.setDutynum2(payVo.getDutynum2());
                            vo.setDutynumday1(payVo.getDutynumday1());
                            vo.setDutynumday2(payVo.getDutynumday2());
                            vo.setRetainnum(payVo.getRetainnum1());
                            vo.setOvertimenum(payVo.getOvertimenum1());
                        }
                        if (i == 1) {
                            vo.setMonth("2");
                            vo.setDutynum1(payVo.getDutynum12());
                            vo.setDutynum2(payVo.getDutynum22());
                            vo.setDutynumday1(payVo.getDutynumday12());
                            vo.setDutynumday2(payVo.getDutynumday22());
                            vo.setRetainnum(payVo.getRetainnum2());
                            vo.setOvertimenum(payVo.getOvertimenum2());
                        }
                        if (i == 2) {
                            vo.setMonth("3");
                            vo.setDutynum1(payVo.getDutynum13());
                            vo.setDutynum2(payVo.getDutynum23());
                            vo.setDutynumday1(payVo.getDutynumday13());
                            vo.setDutynumday2(payVo.getDutynumday23());
                            vo.setRetainnum(payVo.getRetainnum3());
                            vo.setOvertimenum(payVo.getOvertimenum3());
                        }
                    }
                    if (quarter == 2) {
                        if (i == 0) {
                            vo.setMonth("4");
                            vo.setDutynum1(payVo.getDutynum1());
                            vo.setDutynum2(payVo.getDutynum2());
                            vo.setDutynumday1(payVo.getDutynumday1());
                            vo.setDutynumday2(payVo.getDutynumday2());
                            vo.setRetainnum(payVo.getRetainnum1());
                            vo.setOvertimenum(payVo.getOvertimenum1());
                        }
                        if (i == 1) {
                            vo.setMonth("5");
                            vo.setDutynum1(payVo.getDutynum12());
                            vo.setDutynum2(payVo.getDutynum22());
                            vo.setDutynumday1(payVo.getDutynumday12());
                            vo.setDutynumday2(payVo.getDutynumday22());
                            vo.setRetainnum(payVo.getRetainnum2());
                            vo.setOvertimenum(payVo.getOvertimenum2());
                        }
                        if (i == 2) {
                            vo.setMonth("6");
                            vo.setDutynum1(payVo.getDutynum13());
                            vo.setDutynum2(payVo.getDutynum23());
                            vo.setDutynumday1(payVo.getDutynumday13());
                            vo.setDutynumday2(payVo.getDutynumday23());
                            vo.setRetainnum(payVo.getRetainnum3());
                            vo.setOvertimenum(payVo.getOvertimenum3());
                        }
                    }
                    if (quarter == 3) {
                        if (i == 0) {
                            vo.setMonth("7");
                            vo.setDutynum1(payVo.getDutynum1());
                            vo.setDutynum2(payVo.getDutynum2());
                            vo.setDutynumday1(payVo.getDutynumday1());
                            vo.setDutynumday2(payVo.getDutynumday2());
                            vo.setRetainnum(payVo.getRetainnum1());
                            vo.setOvertimenum(payVo.getOvertimenum1());
                        }
                        if (i == 1) {
                            vo.setMonth("8");
                            vo.setDutynum1(payVo.getDutynum12());
                            vo.setDutynum2(payVo.getDutynum22());
                            vo.setDutynumday1(payVo.getDutynumday12());
                            vo.setDutynumday2(payVo.getDutynumday22());
                            vo.setRetainnum(payVo.getRetainnum2());
                            vo.setOvertimenum(payVo.getOvertimenum2());
                        }
                        if (i == 2) {
                            vo.setMonth("9");
                            vo.setDutynum1(payVo.getDutynum13());
                            vo.setDutynum2(payVo.getDutynum23());
                            vo.setDutynumday1(payVo.getDutynumday13());
                            vo.setDutynumday2(payVo.getDutynumday23());
                            vo.setRetainnum(payVo.getRetainnum3());
                            vo.setOvertimenum(payVo.getOvertimenum3());
                        }
                    }
                    if (quarter == 4) {
                        if (i == 0) {
                            vo.setMonth("10");
                            vo.setDutynum1(payVo.getDutynum1());
                            vo.setDutynum2(payVo.getDutynum2());
                            vo.setDutynumday1(payVo.getDutynumday1());
                            vo.setDutynumday2(payVo.getDutynumday2());
                            vo.setRetainnum(payVo.getRetainnum1());
                            vo.setOvertimenum(payVo.getOvertimenum1());
                        }
                        if (i == 1) {
                            vo.setMonth("11");
                            vo.setDutynum1(payVo.getDutynum12());
                            vo.setDutynum2(payVo.getDutynum22());
                            vo.setDutynumday1(payVo.getDutynumday12());
                            vo.setDutynumday2(payVo.getDutynumday22());
                            vo.setRetainnum(payVo.getRetainnum2());
                            vo.setOvertimenum(payVo.getOvertimenum2());
                        }
                        if (i == 2) {
                            vo.setMonth("12");
                            vo.setDutynum1(payVo.getDutynum13());
                            vo.setDutynum2(payVo.getDutynum23());
                            vo.setDutynumday1(payVo.getDutynumday13());
                            vo.setDutynumday2(payVo.getDutynumday23());
                            vo.setRetainnum(payVo.getRetainnum3());
                            vo.setOvertimenum(payVo.getOvertimenum3());
                        }
                    }
                        vo.setStatus(0);
                    if(vo.getRetainnum()!= null && vo.getOvertimenum()!= null && isNumberd(vo.getRetainnum()) && isNumberd(vo.getOvertimenum()))
                        voEntities.add(vo);
                }
                if (userid.equals("")) userid = String.valueOf(payVo.getUserid());
                else userid += "," + payVo.getUserid();
            }
            return userid;
        }
    }

    private String getLastMonth(Integer sqn) {
        String ret = "";
        switch (sqn) {
            case 1:
                ret = "3";
                break;
            case 2:
                ret = "6";
                break;
            case 3:
                ret = "9";
                break;
            case 4:
                ret = "12";
                break;
        }
        return ret;
    }
    //endregion

}
